package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Vector;

public class PoolConnection {

	private Vector<Connection> connections = new Vector<Connection>();
	protected String jdbc;
	protected String servidor;
	protected String usuario;
	protected String password;
	protected int cantCon;
	private static PoolConnection pool;
	
	private PoolConnection(){
		getConfiguration();
		for(int i=0;i<this.cantCon;i++)
			connections.add(connect());
	}
		
	public static PoolConnection getPoolConnecion(){
		if(pool == null)
			pool = new PoolConnection();
		return pool;
	}
	
	private Connection connect(){
		try{
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			String connectionString = this.jdbc + this.servidor;
			Connection con = DriverManager.getConnection(connectionString,this.usuario,this.password);
			return con;
		}
		catch (SQLException e){
			System.out.print("Error: "+e.getMessage());
			System.out.print("Stack Trace: "+e.getStackTrace());
			return null;
		}
		catch (Exception e){
			System.out.print("Error: "+e.getMessage());
			System.out.print("Stack Trace: "+e.getStackTrace());
			return null;
		}
	}
	
	public void getConfiguration(){
		this.usuario = "sa";
		this.password = "12345";
		this.servidor= "192.168.1.31;databaseName=ADMCosechas";
		this.jdbc = "jdbc:sqlserver://";
	}
	
	public void closeConnections(){
		for(int i=0;i<this.connections.size();i++){
			try{
				this.connections.elementAt(i).close();
			}
			catch (Exception e){
				System.out.print("Error: "+e.getMessage());
				System.out.print("Stack Trace: "+e.getStackTrace());
			}
		}
	}
	
	public Connection getConnection(){
		Connection c = null;
		if(this.connections.size()>0)
			c = this.connections.remove(0);
		else{
			c = connect();
			System.out.println("Se ha creado una nueva conexion");
		}
		return c;
	}
	
	public void releaseConnection(Connection c){
		this.connections.add(c);
	}
}
